﻿using Micro.Core.Packages;
using Micro.Modules.Abstractions;
using Micro.Modules.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;

namespace Microsoft.Extensions.DependencyInjection
{
    [DependsOnPacks(typeof(IOCPack))]
    public class ModulesPack : BasePackage
    {

        public override PackLevel Level => PackLevel.Core;
        public override int Order => 10;

        private IModuleCollection Modules;

        public override IServiceCollection AddServices(IServiceCollection services)
        {
            IModuleCollection modules = new ModuleCollection(services);
            modules.Load().Wait();
            services.AddSingleton(modules);
            Modules = modules;


            // 配置 Mvc 选项
            services.Configure<MvcOptions>(options =>
            {
                // 添加应用模型转换器
                //options.Conventions.Add(new DynamicApiControllerApplicationModelConvention());
            });

            //添加模块Controllers
            services.AddControllers().ConfigureApplicationPartManager(options =>
            {
                foreach (var module in modules)
                {
                    if (module.ModuleRuntime.Api != null)
                    {
                        options.ApplicationParts.Add(new AssemblyPart(module.ModuleRuntime.Main));
                    }
                }
            });
            return base.AddServices(services);
        }

        public override IServiceCollection AddServicesed(IServiceCollection services)
        {
            AddModuleServices(services, Modules);
            return services;
        }


        public override void UsePack(WebApplication app)
        {
            //app.
            base.UsePack(app);
        }
        public override void UsePacked(WebApplication app)
        {
            ModuleConfigure(app);
            base.UsePacked(app);
        }



        private void AddModuleServices(IServiceCollection services, IModuleCollection modules)
        {
            foreach (var module in modules)
            {
                //加载模块初始化器
                module?.Initializer?.AddModuleServices(services, module);
            }
        }
        private void ModuleConfigure(WebApplication app)
        {
            IModuleCollection modules = app.Services.GetRequiredService<IModuleCollection>();
            foreach (var module in modules)
            {
                //加载模块初始化器
                module?.Initializer?.Configure(app, module);
            }
        }
    }
}